export default {
    name: 'SimpleCarousel',
    props: {
        items: {
            type: Array,
            default: () => []
        },
        autoplayInterval: {
            type: Number,
            default: 3000
        },
        height: {
            type: String,
            default: '300px'
        },
        fitMode: {
            type: String,
            default: 'cover',
            validator: v => ['cover', 'contain', 'fill'].includes(v)
        }
    },
    setup(props) {
        let timer = null
        const activeIndex = Vue.ref(0)
        
        const startAutoPlay = () => {
            if (props.items.length <= 1) return
            timer = setInterval(() => {
                activeIndex.value = (activeIndex.value + 1) % props.items.length
            }, props.autoplayInterval)
        }
        
        const clearTimer = () => {
            if (timer) {
                clearInterval(timer)
                timer = null
            }
        }
        
        watch(() => props.items, (newVal) => {
            clearTimer()
            activeIndex.value = 0
            if (newVal.length > 1) startAutoPlay()
        })
        
        onMounted(() => {
            if (props.items.length > 1) startAutoPlay()
        })
        
        onBeforeUnmount(() => {
            clearTimer()
        })
        
        return {
            activeIndex
        }
    },
    
    template: `
        <div v-if="items.length" :style="{width: '100%',height: height,overflow: 'hidden',position: 'relative'}" >
            <!-- 轮播容器 -->
            <div :style="{width: items.length * 100 + '%',height: '100%',display: 'flex',transition: 'transform 0.5s ease',transform: 'translateX(-' + activeIndex * 100 + '%)' }">
            
                <!-- 轮播项 -->
                <div v-for="(item, index) in items" :key="index" :style="{width: '100%',height: '100%',flexShrink: 0,position: 'relative'}">
                    <img :src="item" :style="{width: '100%',height: '100%',objectFit: fitMode,position: 'absolute'}"/>
                </div>
            </div>
        </div>
            
        <!-- 空状态 -->
        <div v-else :style="{width: '100%',height: height,display: 'flex',alignItems: 'center',justifyContent: 'center',backgroundColor: '#f5f5f5'}">
            <slot name="empty">
                <span :style="{ color: '#666' }">暂无图片</span>
            </slot>
        </div>
    `
}